import { createStore } from 'vuex'
import api from '@/api'

export default createStore({
  state: () => ({
    token: uni.getStorageSync('token') || null,
    userInfo: uni.getStorageSync('userInfo') || null,
    carList: uni.getStorageSync('carList') || [],
    currentCar: uni.getStorageSync('currentCar') || null
  }),
  
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      uni.setStorageSync('token', token)
    },
    
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      uni.setStorageSync('userInfo', userInfo)
    },
    
    SET_CAR_LIST(state, carList) {
      state.carList = carList
      uni.setStorageSync('carList', carList)
    },
    
    SET_CURRENT_CAR(state, car) {
      state.currentCar = car
      uni.setStorageSync('currentCar', car)
    },
    
    CLEAR_AUTH(state) {
      state.token = null
      state.userInfo = null
      state.carList = []
      state.currentCar = null
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('carList')
      uni.removeStorageSync('currentCar')
    }
  },
  
  actions: {
    // 登录
    async login({ commit }, { username, password }) {
      try {
        const res = await api.login({ username, password })
        commit('SET_TOKEN', res.data.token)
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 获取用户信息
    async fetchUserInfo({ commit }) {
      try {
        const res = await api.getUserInfo()
        commit('SET_USER_INFO', res.data)
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 获取车辆列表
    async fetchCarList({ commit }) {
      try {
        const res = await api.getCarList()
        commit('SET_CAR_LIST', res.data)
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 添加车辆
    async addCar({ commit, state }, carData) {
      try {
        const res = await api.addCar(carData)
        const updatedList = [...state.carList, res.data]
        commit('SET_CAR_LIST', updatedList)
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 删除车辆
    async deleteCar({ commit, state }, carId) {
      try {
        await api.deleteCar(carId)
        const updatedList = state.carList.filter(car => car.id !== carId)
        commit('SET_CAR_LIST', updatedList)
        
        // 如果删除的是当前选中的车辆，清空currentCar
        if (state.currentCar && state.currentCar.id === carId) {
          commit('SET_CURRENT_CAR', null)
        }
      } catch (error) {
        throw error
      }
    },
    
    // 退出登录
    logout({ commit }) {
      commit('CLEAR_AUTH')
      uni.reLaunch({
        url: '/pages/login/index'
      })
    }
  },
  
  getters: {
    isLoggedIn: state => !!state.token,
    getUserInfo: state => state.userInfo,
    getCarList: state => state.carList,
    getCurrentCar: state => state.currentCar
  }
})